package com.mjk.common.web.getway.utils.loadbalancer.impl;

import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.web.getway.utils.loadbalancer.AbstractLoadBalancer;
import org.springframework.util.CollectionUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 静态负载均衡示例算法：轮询
 */
public class RoundRobinLoadBalance extends AbstractLoadBalancer  {


    public RoundRobinLoadBalance() {
        servers = new ConcurrentHashMap<>();
        currentIndex = new ConcurrentHashMap<>();
        ip2EvnMap = new ConcurrentHashMap<>();
    }

    @Override
    public String getNextServer(String key) {
        //获取环境ID
        if(ObjectUtils.isNotEmpty(key) && servers.containsKey(key)) {
            String evnId = ip2EvnMap.get(key);
            if(CollectionUtils.isEmpty(servers.get(key))){
                BizLogger.error("robin load balance for clientIp:"+key+"having no service");
                return null;
            }
            String server = servers.get(key).get(currentIndex.get(evnId));
            currentIndex.put(evnId, (currentIndex.get(evnId) + 1) % servers.get(key).size());
            return server;
        }else{
            return null;
        }
    }


}
